﻿using System.Web;

using Tools.Json;

using System.IO;
using System;

namespace SY.WebSite.Web.Handler
{
    public class UploadHandler : InternalWebHandler, IHttpHandler
    {
        public new void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            switch (Action)
            {
                case "uploadFile":
                    UploadFile();
                    break;
            }

            context.Response.End();
        }
        
        /// <summary>
        /// 上传文件
        /// </summary>
        private void UploadFile()
        {
            JsonTransfer jt = new JsonTransfer();
            try
            {
                string fileName = Request.Files[0].FileName;
                string mimeType = fileName.Substring(fileName.LastIndexOf("."));
                int fileSize = Request.Files[0].ContentLength;

                if (fileSize > Convert.ToInt32(Common.Settings.KeyValues["attachment_upload_maxsize"]))
                {
                    jt.SetError("当前文件大小为：" + fileSize + "字节，超出系统最大可上传字节数：" + Common.Settings.KeyValues["attachment_upload_maxsize"] + "字节");
                    Response.Write(jt);
                    return;
                }
                if (!Common.Settings.KeyValues["attachment_upload_type"].ToString().Contains("|" + mimeType + "|"))
                {
                    jt.SetError("当前文件类型为：" + mimeType + "，系统允许上传文件类型有：" + Common.Settings.KeyValues["attachment_upload_type"]);
                    Response.Write(jt);
                    return;
                }

                string filePath = HttpContext.Current.Server.MapPath(Common.Settings.KeyValues["attachment_upload_path"] + "/attachment/");
                if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(filePath);
                }
                string saveName = Guid.NewGuid() + mimeType;
                Request.Files[0].SaveAs(filePath + saveName);
                jt.Add("success", "success");
                jt.Add("url", Common.Settings.DomainUrl + Common.Settings.KeyValues["attachment_upload_path"] + "/attachment/" + saveName);
            }
            catch (Exception ex)
            {
                jt.SetError(ex.Message);
            }
            Response.Write(jt);
        }
    }
}